﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using NPOI.SS.Formula.Functions;
using NPOI.XWPF.UserModel;
using Match = System.Text.RegularExpressions.Match;

namespace FillWordDataByTemplate
{
    /// <summary>
    /// 
    /// </summary>
    public class XwpfTest
    {
        // XWPFDocument
        // HWPFDocument


        /// <summary>
        /// 
        /// </summary>
        public void testTemplateWrite()
        {
            //替换字典 ${电话} ${罚款}
            Dictionary<string, Object> params3 = new Dictionary<String, Object>();
            params3.Add("${电话}", "13423433034");
            params3.Add("${罚款}", "99.85");

            //读
            string filePath = @"E:\Users\Documents\Visual Studio 2013\Projects\用NPOI读写Word\FillWordDataByTemplate\_files_\这是模板2.docx";
            //FileStream fs_template = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            Stream fs_template = File.OpenRead(filePath);
            XWPFDocument doc2 = new XWPFDocument(fs_template);

            //foreach (XWPFParagraph paragraph in doc2.Paragraphs)
            //{
            //    string searchText = paragraph.Text;//"${电话}";
            //    if (String.Compare(searchText, "${电话}", StringComparison.OrdinalIgnoreCase) == 0)
            //    {
            //        string newText = searchText.Replace("${电话}", "13423433034");
            //        paragraph.ReplaceText(searchText, newText);
            //    }
            //}

            //替换段落里面的变量  
            this.replaceInPara(doc2, params3);

            //替换表格里面的变量  
            //this.replaceInTable(doc2, params3); 

            //写
            string fileNew =
                @"E:\Users\Documents\Visual Studio 2013\Projects\用NPOI读写Word\FillWordDataByTemplate\_files_\这是新文件" +
                DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".docx";
            FileStream fs_newfile = new FileStream(fileNew, 
                FileMode.CreateNew, 
                FileAccess.ReadWrite
                );
            doc2.Write(fs_newfile);

            //关
            fs_template.Close();
            fs_newfile.Close();
        }

        /// <summary>
        /// 替换段落里面的变量
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="params2"></param>
        private void replaceInPara(XWPFDocument doc, Dictionary<String, Object> params2)
        {
            IEnumerator<XWPFParagraph> iterator = doc.GetParagraphsEnumerator();
            XWPFParagraph para;
            while (iterator.MoveNext())
            {
                para = iterator.Current;
                //
                //Debug.WriteLine("----------------------------------------");
                //Debug.WriteLine(para.Text);
                //Debug.WriteLine("----------------------------------------");

                //
                replaceInPara(para, params2);  
            }
        }

        /// <summary>
        /// 正则匹配字符串
        /// </summary>
        private const string pattern = "\\$\\{(.+?)\\}";
        private Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

        /// <summary>
        /// 替换段落里面的变量
        /// </summary>
        /// <param name="para"></param>
        /// <param name="params2"></param>
        private void replaceInPara(XWPFParagraph para, Dictionary<String, Object> params2)
        {
            IList<XWPFRun> runs;
            string text = para.Text;

            MatchCollection mc =  reg.Matches(text);
            foreach (Match match in mc)
            {
                //
                if (match.Success)
                {
                    Debug.WriteLine("match.Success=" + match.Success);
                }
                //string r = match.Result();

                //
                runs = para.Runs;
                for (int i = 0; i < runs.Count; i++)
                {
                    XWPFRun run = runs[i];
                    string runText = run.Text;
                    Debug.WriteLine("runText=" + runText);





                    //matcher = this.matcher(runText);
                    //match.Matches(text);
                    //if (matcher.find())
                    //{
                    //    while ((matcher = this.matcher(runText)).find())
                    //    {
                    //        runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))))
                    //        ;
                    //    }
                    //    //直接调用XWPFRun的setText()方法设置文本时，在底层会重新创建一个XWPFRun，把文本附加在当前文本后面，  
                    //    //所以我们不能直接设值，需要先删除当前run,然后再自己手动插入一个新的run。  
                    //    para.removeRun(i);
                    //    para.insertNewRun(i).setText(runText);
                    //}


                }//for XWPFRun
                
            } //foreach
        }

        #region x
        ///// <summary>
        ///// 替换段落里面的变量
        ///// </summary>
        ///// <param name="doc">要替换的文档 </param>
        ///// <param name="params2">参数</param>
        //private void replaceInPara(XWPFDocument doc, Dictionary<String, Object> params2)
        //{
        //    IEnumerator<XWPFParagraph> iterator = doc.GetParagraphsEnumerator();
        //    XWPFParagraph para;
        //    while (iterator.MoveNext())
        //    {
        //        para = iterator.Current;
        //        replaceInPara(para, params2);
        //    }
        //}
        #endregion

        #region x
        ///// <summary>
        ///// 替换段落里面的变量
        ///// </summary>
        ///// <param name="para">要替换的段落</param>
        ///// <param name="params2">参数</param>
        //private void replaceInPara(XWPFParagraph para, Dictionary<String, Object> params2)
        //{
        //    //
        //    //
        //    IList<XWPFRun> runs;
        //    //Matcher matcher;

        //    string text = para.ParagraphText;
        //    Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        //    //Match result = Regex.Match(text,pattern);
        //    MatchCollection mc =  reg.Matches(text);
        //    foreach (Match m in mc)
        //    {
        //        //if (result.)
        //        //{
        //            runs = para.Runs;
        //            for (int i = 0; i < runs.Count; i++)
        //            {
        //                XWPFRun run = runs[i];
        //                String runText = run.Text;
        //                //matcher = this.matcher(runText);

        //                string s = Regex.Replace(m.Groups[0].ToString(),"","",RegexOptions.IgnoreCase);

        //                //if (matcher.find())
        //                //{
        //                //    while ((matcher = this.matcher(runText)).find())
        //                //    {
        //                //        runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))))
        //                //        ;
        //                //    }
        //                //    //直接调用XWPFRun的setText()方法设置文本时，在底层会重新创建一个XWPFRun，把文本附加在当前文本后面，  
        //                //    //所以我们不能直接设值，需要先删除当前run,然后再自己手动插入一个新的run。  
        //                //    para.removeRun(i);
        //                //    para.insertNewRun(i).setText(runText);
        //                //}
        //            }
        //        //}
        //    }
        //}
        #endregion



    }

}
